<?php

namespace Thenbsp\Wechat\Payment;

use Thenbsp\Wechat\Exception\PaymentException;

class Business
{
    /**
     * 商户基本信息
     */
    protected $params;

    /**
     * 有效的参数
     */
    protected $valids = array('appid', 'appsecret', 'mch_id', 'mch_key');

    /**
     * 商户证书 cert
     */
    protected $clientCert;

    /**
     * 商户证书 key
     */
    protected $clientKey;

    /**
     * 构造方法
     */
    public function __construct() { }

    /**
     * 获取参数
     */
    public function getParams($paramName = null, $default = null)
    {
        if( null !== $paramName ) {
            return $this->hasParams($paramName) ?
                $this->params[$paramName] : $default;
        }
        return $this->params;
    }

    /**
     * 检测是否包含指定参数
     */
    public function hasParams($paramName)
    {
        return isset($this->params[$paramName]);
    }

    /**
     * 设置商户证书 cert
     */
    public function setClientCert($filepath)
    {
        if( !file_exists($filepath) ) {
            throw new PaymentException(sprintf('client_cert "%s" is not found', $filepath));
        }

        $this->clientCert = $filepath;
    }

    /**
     * 获取商户证书 cert
     */
    public function getClientCert()
    {
        return $this->clientCert;
    }

    /**
     * 设置商户证书 key
     */
    public function setClientKey($filepath)
    {
        if( !file_exists($filepath) ) {
            throw new PaymentException(sprintf('client_key "%s" is not found', $filepath));
        }

        $this->clientKey = $filepath;
    }

    /**
     * 获取商户证书 key
     */
    public function getClientKey()
    {
        return $this->clientKey;
    }

    /**
     * 检测参数值是否有效
     */
    public function checkParams()
    {
        foreach($this->valids AS $paramName) {
            if( !$this->hasParams($paramName) ) {
                throw new PaymentException(sprintf('"%s" is required', $paramName));
            }
        }
    }

    /**
     * 魔术方法
     */
    public function __call($method, $arguments)
    {
        if( !in_array($method, $this->valids) ) {
            throw new PaymentException(sprintf('Invalid arguments "%s"', $method));
        }

        $this->params[$method] = $arguments[0];

        return $this;
    }
}